<template>
  <div class='sub-category'>
    <div class="container">
      <!-- 面包屑 -->
      <SubBread />
      <!-- 筛选区 -->
      <SubFilter @attrs="attrs"/>
      <!-- 结果区域 -->
      <div class="goods-list">
        <!-- 排序 -->
        <SubSort @sort-change="sortChange"/>
        <!-- 列表 -->
        <ul>
          <li v-for="item in list" :key="item.id" >
            <GoodsItem :goods="item" />
          </li>
        </ul>
        <XtxInfiniteLoading :loading="loading" :finished="finished" @infinite="onLoad"/>
      </div>
    </div>
  </div>
</template>

<script>
import XtxInfiniteLoading from '@/components/xtx-infinite-loading.vue'
import GoodsItem from './components/goods-item.vue'
import SubBread from './components/sub-bread'
import SubFilter from './components/sub-filter.vue'
import SubSort from './components/sub-sort.vue'
import { ref, watch } from 'vue'
import { findSubCategoryGoods } from '@/api/category'
import { useRoute } from 'vue-router'

export default {
  name: 'SubCategory',
  components: { SubBread, SubFilter, SubSort, GoodsItem, XtxInfiniteLoading },
  setup () {
    const loading = ref(false)
    const finished = ref(false)
    const list = ref([])
    const route = useRoute()
    let data = {
      page: 1,
      pageSize: 20
    }
    const onLoad = async () => {
      loading.value = true
      const { result } = await findSubCategoryGoods(data)
      list.value.push(...result.items)
      loading.value = false
      if (result.items.length < data.pageSize) {
        finished.value = true
        return
      }
      data.page++
    }
    const attrs = (attrs) => {
      data = {
        page: 1,
        pageSize: 20,
        ...attrs
      }
      list.value = []
      onLoad()
      console.log(data)
    }
    const sortChange = async (val) => {
      data = {
        page: 1,
        pageSize: 20,
        ...val
      }
      finished.value = false
      list.value = []
      onLoad()
    }
    watch(() => route.params.id, () => {
      data = {
        page: 1,
        pageSize: 20,
        categoryId: route.params.id
      }
      finished.value = false
      list.value = []
      onLoad()
    }, {
      immediate: true
    })
    return { sortChange, loading, finished, onLoad, list, attrs }
  }
}
</script>

<style scoped lang='less'>
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
